﻿using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections.Generic;

namespace System
{
    public static class TypeExtensions
    {
        public static bool CheckIfAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                && type.IsGenericType && type.Name.Contains("AnonymousType")
                && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }

        public static bool IsAnonymousType(this Type type)
        {
            return CheckIfAnonymousType(type);
        }

        public static IDictionary<string, string> GetPropertiesToDict(this Type type,object sourceobj)
        {
            if (type == null)
                throw new ArgumentNullException("type");
            IDictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var pi in type.GetProperties())
            {
                dict.Add(pi.Name, pi.GetValue(sourceobj, null).ToString());
            }
            return dict;
        }
    }
}
